//
//  MYAccountTool.m
//  奇闻
//
//  Created by 似水灵修 on 14-11-26.
//  Copyright (c) 2014年 MingYueGuCheng. All rights reserved.
//

#import "MYAccountTool.h"
#import "MYAccountParam.h"
#import "MJExtension.h"
#import "MYHttpTool.h"
//帐户信息在沙盒中的存储位置
#define MYAccountPlace [MYDocument stringByAppendingPathComponent:@"account.data"]
@implementation MYAccountTool
/**
 *  存储帐户信息
 */
+ (void)save:(MYAccount *)account
{
    [NSKeyedArchiver archiveRootObject:account toFile:MYAccountPlace];
}
/**
 *  读取帐户信息
 */
+ (MYAccount *)account
{
    MYAccount *account = [NSKeyedUnarchiver unarchiveObjectWithFile:MYAccountPlace];
    //账号是否过期
    if ([account.expires_time compare:[NSDate date]] != NSOrderedDescending) { //过期
        account = nil;
    }
//     MYLog(@"%@", MYAccountPlace);
    return account;
}
/**
 *  获取accessToken
 *
 *  @param code    requestToken
 *  @param success 成功的回调
 *  @param failure 失败的回调
 */
+ (void)accessTokenWithCode:(id)code success:(void (^)())success failure:(void (^)(NSError *))failure
{
    MYAccountParam *param = [[MYAccountParam alloc] init];
    param.client_id = MYAppKey;
    param.client_secret = MYAPPSecret;
    param.redirect_uri = MYRedirectURI;
    param.grant_type = @"authorization_code";
    param.code = code;
    //发送POST请求
    //OAuth2（开发指南）获取授权	oauth2/access_token
    [MYHttpTool POST:@"https://api.weibo.com/oauth2/access_token" parameters:param.keyValues success:^(id responseObject) {
        //存储用户信息
        MYAccount *account = [MYAccount accountWithDict:responseObject];
        [MYAccountTool save:account];
        // 选择进入新特性还是首页
        // 判断有没有新特性,从而选择窗口的根控制器
        if (success) {
            success();
        }
    } failure:^(NSError *error) {
        if (failure) {
            failure(error);
        }
    }];
}
@end
